<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>请求拦截器</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <button id="btn">请求</button>
    <script>
        //创建axios实例
        //公共配置
        const myAxios = axios.create({
            baseURL: "/axios",
            timeout: 10000,
            headers: {}
        })
        //配置拦截
        myAxios.interceptors.request.use((config) => {
            config.headers.token = "3123.121312.213"
            return config
        })
        myAxios.interceptors.response.use((response) => {

            return response.data
        },(err)=>{
            return Promise.reject(err)
        })

        btn.onclick =async function () {
            try {
                const result = await myAxios.get('/get', {
                params: {
                    userId: "001"
                }}).then(resolve=>{
                    if(resolve.code===404){
                       return console.log(resolve.msg);
                    }
                    if(resolve.code===403){
                       return alert(resolve.msg);
                    }
                    document.body.innerHTML += JSON.stringify(resolve.data)
                })
            } catch (err) {
                
            }
        }
    </script>
</body>

</html>